<template>
  <div class="resume-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">我的简历</span>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              添加简历
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="简历类型">
            <el-select 
              v-model="searchForm.resume_type" 
              placeholder="全部类型" 
              clearable
              style="width: 150px"
              @change="handleSearch"
            >
              <el-option label="上传简历" value="uploaded" />
              <el-option label="在线生成" value="generated" />
            </el-select>
          </el-form-item>

          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="全部状态" 
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option
                v-for="status in RESUME_STATUS_OPTIONS"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 简历列表 -->
      <div class="resume-content" v-loading="loading">
        <div v-if="resumeList.length === 0" class="empty-state">
          <el-empty description="暂无简历">
            <el-button type="primary" @click="showCreateDialog = true">
              创建第一份简历
            </el-button>
          </el-empty>
        </div>

        <div v-else class="resume-grid">
          <el-card
            v-for="resume in resumeList"
            :key="resume.id"
            class="resume-card"
            shadow="hover"
            :class="{ 'card-clickable': resume.resume_type === 'generated' }"
            @click="handleCardClick(resume)">
            <!-- 卡片头部 -->
            <template #header>
              <div class="card-header">
                <div class="header-left">
                  <div class="resume-title">{{ resume.title || '未命名简历' }}</div>
                  <div class="resume-meta">
                    <el-tag
                      :type="resume.resume_type === 'uploaded' ? 'warning' : 'success'"
                      size="small"
                    >
                      {{ resume.resume_type === 'uploaded' ? '上传简历' : '在线生成' }}
                    </el-tag>
                    <ResumeStatusTag
                      :status="resume.status"
                      size="small"
                      :show-icon="true"
                      style="margin-left: 8px"
                    />
                    <!-- 审核结果提示 -->
                    <el-tooltip
                      v-if="resume.review_comments && ['approved', 'rejected', 'needs_revision'].includes(resume.status)"
                      :content="resume.review_comments"
                      placement="top"
                    >
                      <el-icon style="margin-left: 4px; color: var(--color-info)">
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </div>

              </div>
            </template>

            <!-- 卡片内容 -->
            <div class="card-content">
              <!-- 投递岗位 -->
              <div class="info-row">
                <span class="info-label">投递岗位：</span>
                <span class="info-value">{{ getJobIntention(resume) }}</span>
              </div>

              <!-- 当前步骤 -->
              <div class="info-row">
                <span class="info-label">当前步骤：</span>
                <span class="info-value">{{ getCurrentStepName(resume.current_step) }}</span>
              </div>

              <!-- 更新时间 -->
              <div class="info-row">
                <span class="info-label">更新时间：</span>
                <span class="info-value">{{ formatTime(resume.updated_at) }}</span>
              </div>

              <!-- 完成度（仅在线生成简历显示） -->
              <div class="info-row" v-if="resume.resume_type === 'generated'">
                <span class="info-label">完成度：</span>
                <div class="completion-info">
                  <el-progress
                    :percentage="resume.completion_rate || 0"
                    :stroke-width="6"
                    :show-text="false"
                    :status="getCompletionStatus(resume.completion_rate)"
                    style="width: 100px"
                  />
                  <span class="percentage" :class="getCompletionClass(resume.completion_rate)">
                    {{ resume.completion_rate || 0 }}%
                  </span>
                  <el-tooltip
                    v-if="(resume.completion_rate || 0) < 80"
                    content="完成度需达到80%才能提交审核"
                    placement="top"
                  >
                    <el-icon class="completion-tip" style="margin-left: 4px; color: var(--color-warning)">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </div>
              </div>

              <!-- 模板信息 -->
              <div class="info-row" v-if="resume.template_name">
                <span class="info-label">使用模板：</span>
                <span class="info-value">{{ resume.template_name }}</span>
              </div>
            </div>

            <!-- 提交审核按钮（在卡片主体内容底部） -->
            <div class="submit-section" v-if="shouldShowSubmitButton(resume)">
              <el-tooltip
                :content="getSubmitReviewTooltip(resume)"
                placement="top"
                :disabled="canSubmitReview(resume)"
              >
                <el-button
                  :type="canSubmitReview(resume) ? 'success' : 'warning'"
                  size="small"
                  @click.stop="handleSubmitReview(resume)"
                  :disabled="!canSubmitReview(resume)"
                  :class="{ 'submit-ready': canSubmitReview(resume) }"
                  style="width: 100%"
                >
                  <el-icon><Check /></el-icon>
                  {{ canSubmitReview(resume) ? '提交审核' : '完善简历' }}
                  <el-tag
                    v-if="!canSubmitReview(resume) && resume.resume_type === 'generated'"
                    size="small"
                    type="info"
                    style="margin-left: 4px"
                  >
                    {{ Math.round(parseFloat(resume.completion_rate?.toString() || '0')) }}%
                  </el-tag>
                </el-button>
              </el-tooltip>
            </div>

            <!-- 卡片底部操作按钮 -->
            <template #footer>
              <div class="footer-actions">
                <!-- 预览按钮 -->
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="handlePreview(resume)"
                  :disabled="!canPreview(resume)"
                >
                  <el-icon><View /></el-icon>
                  预览
                </el-button>

                <!-- 更多操作下拉菜单 -->
                <div
                  class="dropdown-wrapper"
                  @click.stop.prevent
                  @mousedown.stop
                  @mouseup.stop
                >
                  <el-dropdown
                    @command="(command) => handleDropdownCommand(command, resume)"
                    trigger="click"
                    placement="bottom-end"
                    @click.stop.prevent
                  >
                    <el-button
                      size="small"
                      type="info"
                      plain
                      @click.stop.prevent
                    >
                      <el-icon><MoreFilled /></el-icon>
                      更多操作...
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="action in getAllSecondaryActions(resume)"
                          :key="action.command"
                          :command="action.command"
                          :disabled="action.disabled"
                        >
                          <el-icon>
                            <component :is="action.icon" />
                          </el-icon>
                          {{ action.label }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>




              </div>
            </template>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="pagination.total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 创建简历对话框 -->
    <CreateResumeDialog
      v-model="showCreateDialog"
      @success="handleCreateSuccess"
    />

    <!-- 简历预览对话框 -->
    <EnhancedResumePreview
      v-model:visible="showPreviewDialog"
      :file-url="previewFileUrl"
      :file-name="previewFileName"
      :title="previewTitle"
      @download="handlePreviewDownload"
    />

    <!-- AI评估岗位选择对话框 -->
    <JobSelectionDialog
      v-model="showJobSelectionDialog"
      :resume="currentEvaluationResume"
      @confirm="handleJobSelectionConfirm"
    />

    <!-- AI评估结果对话框 -->
    <AIEvaluationResultDialog
      v-model="showEvaluationResultDialog"
      :resume="currentEvaluationResume"
      @download="handleDownloadEvaluationReport"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onActivated, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading, ElNotification } from 'element-plus'
// import { showSuccess, showError, showConfirm, handleApiError } from '@/utils/message' // 暂时注释，后续可能使用
import {
  Plus,
  Search,
  Refresh,
  View,
  Edit,
  Delete,
  Download,
  Document,
  Check,
  MoreFilled,
  InfoFilled,
  Warning,
  UserFilled
} from '@element-plus/icons-vue'
import { resumeApi, type Resume, RESUME_STATUS_OPTIONS } from '@/api/resume'
import { formatTime } from '@/utils/format'
import CreateResumeDialog from './components/CreateResumeDialog.vue'
import EnhancedResumePreview from '@/components/EnhancedResumePreview.vue'
import ResumeStatusTag from '@/components/ResumeStatusTag.vue'
import JobSelectionDialog from './components/JobSelectionDialog.vue'
import AIEvaluationResultDialog from './components/AIEvaluationResultDialog.vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const resumeList = ref<Resume[]>([])
const showCreateDialog = ref(false)

// 预览相关数据
const showPreviewDialog = ref(false)
const previewFileUrl = ref('')
const previewFileName = ref('')
const previewTitle = ref('')
const currentPreviewResume = ref<Resume | null>(null)

// AI评估相关数据
const showJobSelectionDialog = ref(false)
const showEvaluationResultDialog = ref(false)
const currentEvaluationResume = ref<Resume | null>(null)

// 搜索表单
const searchForm = reactive({
  resume_type: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 12,
  total: 0
})

// 状态相关函数已移至 ResumeStatusTag 组件和 API 工具函数中

// 获取求职意向
const getJobIntention = (resume: Resume): string => {
  // 根据简历类型和模板推断求职意向
  if (resume.template_name) {
    return `${resume.template_name}相关岗位`
  }
  return resume.resume_type === 'generated' ? '软件开发工程师' : '待设置'
}

// 获取当前步骤名称
const getCurrentStepName = (step: number): string => {
  const stepNames = [
    '基本信息',
    '教育背景',
    '专业技能',
    '项目经验',
    '工作经验',
    '获奖经历',
    '自我介绍'
  ]
  return stepNames[step - 1] || '未开始'
}

// 判断是否可以提交审核
const canSubmitReview = (resume: Resume): boolean => {
  // 只有草稿、制作中、需修改的简历可以提交审核
  if (!['draft', 'in_progress', 'needs_revision'].includes(resume.status)) {
    return false
  }

  if (resume.resume_type === 'uploaded') {
    return !!resume.uploaded_file
  } else {
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    return completionRate >= 80
  }
}

// 判断是否应该显示提交审核按钮
const shouldShowSubmitButton = (resume: Resume): boolean => {
  // 只有草稿、制作中、需修改的简历才显示提交审核按钮
  return [ 'draft', 'in_progress', 'needs_revision'].includes(resume.status)
}

// 获取提交审核按钮的提示信息
const getSubmitReviewTooltip = (resume: Resume): string => {
  if (!['draft', 'in_progress', 'needs_revision'].includes(resume.status)) {
    return '当前状态不允许提交审核'
  }

  if (resume.resume_type === 'uploaded') {
    if (!resume.uploaded_file) {
      return '请先上传简历文件'
    }
  } else {
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    if (completionRate < 80) {
      return `简历完成度不足80%（当前：${completionRate}%），请继续完善简历内容`
    }
  }

  return '点击提交简历进行审核'
}



// 获取完成度进度条状态
const getCompletionStatus = (completionRate: number | undefined): 'success' | 'warning' | 'exception' | '' => {
  const rate = completionRate || 0
  if (rate >= 80) return 'success'
  if (rate >= 60) return 'warning'
  return 'exception'
}

// 获取完成度文字样式类
const getCompletionClass = (completionRate: number | undefined): string => {
  const rate = completionRate || 0
  if (rate >= 80) return 'completion-success'
  if (rate >= 60) return 'completion-warning'
  return 'completion-danger'
}

// 获取所有次要操作按钮列表（合并原右上角和底部的操作）
const getAllSecondaryActions = (resume: Resume) => {
  const actions = []

  // 下载功能
  actions.push({
    command: 'download',
    label: '下载简历',
    icon: 'Download',
    disabled: !canDownload(resume)
  })

  // 老师审核（原右上角操作）
  if (shouldShowSubmitButton(resume)) {
    actions.push({
      command: 'teacherReview',
      label: '提交老师审核',
      icon: 'UserFilled',
      disabled: !canSubmitReview(resume)
    })
  }

  // 历史版本
  if (hasVersions(resume)) {
    actions.push({
      command: 'viewVersions',
      label: '历史版本',
      icon: 'Document',
      disabled: false
    })
  }

  // AI评估功能
  if (canAIEvaluation(resume)) {
    actions.push({
      command: 'aiEvaluation',
      label: 'AI评估',
      icon: 'Check',
      disabled: resume.ai_evaluation_status === 'in_progress'
    })
  }

  // 查看AI评估结果
  if (resume.ai_evaluation_status === 'completed' && resume.ai_evaluation_file) {
    actions.push({
      command: 'viewAIEvaluation',
      label: '查看AI评估结果',
      icon: 'Document',
      disabled: false
    })
  }

  // 下载AI评估报告
  if (resume.ai_evaluation_status === 'completed' && resume.ai_evaluation_file) {
    actions.push({
      command: 'downloadAIEvaluation',
      label: '下载AI评估报告',
      icon: 'Download',
      disabled: false
    })
  }

  // 查看审核结果
  if (['approved', 'rejected', 'needs_revision'].includes(resume.status)) {
    actions.push({
      command: 'viewReviewResult',
      label: '查看审核结果',
      icon: 'View',
      disabled: false
    })
  }

  // 编辑功能（原底部按钮，现在移到更多操作中）
  if (resume.resume_type === 'generated') {
    actions.push({
      command: 'edit',
      label: '编辑简历',
      icon: 'Edit',
      disabled: false
    })
  }

  // 删除简历（原右上角操作，现在条件更宽松）
  actions.push({
    command: 'delete',
    label: '删除简历',
    icon: 'Delete',
    disabled: false
  })

  return actions
}



// 处理下拉菜单命令
const handleDropdownCommand = (command: string, resume: Resume) => {
  switch (command) {
    case 'download':
      handleDownload(resume)
      break
    case 'viewVersions':
      handleViewVersions(resume)
      break
    case 'aiEvaluation':
      handleAIEvaluation(resume)
      break
    case 'viewAIEvaluation':
      handleViewAIEvaluation(resume)
      break
    case 'downloadAIEvaluation':
      handleDownloadEvaluationReport(resume)
      break
    case 'viewReviewResult':
      handleViewReviewResult(resume)
      break
    case 'delete':
      handleDelete(resume)
      break
    case 'teacherReview':
      handleSubmitReview(resume)
      break
    case 'aiReview':
      handleAIReview(resume)
      break
    case 'edit':
      handleEdit(resume)
      break
  }
}

// 判断是否可以AI评估
const canAIEvaluation = (resume: Resume): boolean => {
  if (resume.resume_type === 'uploaded') {
    // 上传简历：有上传文件就可以评估
    return !!resume.uploaded_file
  } else {
    // 在线生成简历：完成度90%以上并且已生成附件简历
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    const hasGeneratedFile = !!(resume.generated_file_url || resume.generated_file)
    return completionRate >= 90 && hasGeneratedFile
  }
}

// 判断是否有历史版本
const hasVersions = (resume: Resume): boolean => {
  // 如果简历曾经提交过审核，就会有版本记录
  return ['pending_review', 'under_review', 'approved', 'rejected', 'needs_revision'].includes(resume.status)
}

// 获取简历列表
const fetchResumeList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    // 清理空值
    Object.keys(params).forEach(key => {
      if ((params as any)[key] === '' || (params as any)[key] === null) {
        delete (params as any)[key]
      }
    })

    const response = await resumeApi.getResumeList(params)
    const data = response.data || response
    resumeList.value = data.results || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('获取简历列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchResumeList()
}

// 重置搜索
const handleReset = () => {
  searchForm.resume_type = ''
  searchForm.status = ''
  pagination.page = 1
  fetchResumeList()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchResumeList()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchResumeList()
}

// 处理卡片点击
const handleCardClick = (resume: Resume, event?: Event) => {
  // 添加调试信息
  console.log('卡片点击事件触发:', resume.title, event?.target)

  if (resume.resume_type === 'generated') {
    // 在线生成的简历，跳转到编辑页面
    router.push(`/resume/builder/${resume.id}`)
  } else {
    // 上传的简历，跳转到详情页面
    router.push(`/resume/detail/${resume.id}`)
  }
}

// 已移除未使用的 handleResumeClick 函数

// 处理编辑
const handleEdit = (resume: Resume) => {
  if (resume.resume_type === 'generated') {
    router.push(`/resume/builder/${resume.id}`)
  } else {
    router.push(`/resume/detail/${resume.id}`)
  }
}

// 处理下载
const handleDownload = async (resume: Resume) => {
  try {
    if (resume.resume_type === 'generated') {
      // 在线生成的简历
      if (resume.generated_file_url || resume.generated_file) {
        // 已经有生成的文件，直接下载
        await generateAndDownloadWord(resume)
      } else {
        // 没有生成文件，检查完成度
        const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
        if (completionRate >= 80) {
          // 简历完成度达到80%以上，可以生成Word文档
          await generateAndDownloadWord(resume)
        } else {
          ElMessage.warning(`简历完成度仅${completionRate}%，至少需要80%才能下载`)
        }
      }
    } else {
      // 上传的简历
      if (resume.uploaded_file) {
        try {
          // 直接调用下载API，后端会返回文件内容
          await downloadResumeFile(resume.id, resume.title)
          ElMessage.success('文件下载成功')
        } catch (error: any) {
          console.error('下载API调用失败:', error)
          ElMessage.error('下载失败：' + (error.response?.data?.error || error.message))
        }
      } else {
        ElMessage.warning('暂无可下载的文件')
      }
    }
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 生成并下载Word文档
const generateAndDownloadWord = async (resume: Resume) => {
  // 如果已经有生成的文件，直接下载
  if (resume.generated_file_url) {
    const downloadUrl = `/api/resume-management/resumes/${resume.id}/download-generated/`
    const fileName = resume.generated_file_name || `${resume.title}.docx`
    await downloadGeneratedFile(downloadUrl, fileName)
    ElMessage.success('文档下载成功')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在生成Word文档，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const response = await resumeApi.generateResume(resume.id, 'docx')
    const data = response.data || response

    if (data.download_url) {
      // 下载生成的文件
      const downloadUrl = `/api/resume-management/resumes/${resume.id}/download-generated/`
      await downloadGeneratedFile(downloadUrl, data.file_name)
      ElMessage.success('Word文档生成并下载成功')

      // 更新简历信息
      await fetchResumeList()
    }
  } catch (error: any) {
    console.error('生成Word文档失败:', error)
    ElMessage.error(error.response?.data?.error || '生成Word文档失败')
  } finally {
    loading.close()
  }
}

// 下载简历文件（上传的简历）
const downloadResumeFile = async (resumeId: number, fileName: string) => {
  try {
    const userStore = useUserStore()
    const response = await fetch(`/api/resume-management/resumes/${resumeId}/download/`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url

    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers.get('content-disposition')
    let downloadFileName = fileName
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename="(.+)"/)
      if (fileNameMatch) {
        downloadFileName = fileNameMatch[1]
      }
    }

    link.download = downloadFileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载文件错误:', error)
    throw error
  }
}

// 下载生成的文件
const downloadGeneratedFile = async (downloadUrl: string, fileName: string) => {
  try {
    const userStore = useUserStore()
    const response = await fetch(downloadUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载文件错误:', error)
    ElMessage.error('下载失败')
  }
}

// 处理预览
const handlePreview = async (resume: Resume) => {
  if (!canPreview(resume)) {
    ElMessage.warning('暂无可预览的文件')
    return
  }

  // 设置预览数据
  currentPreviewResume.value = resume
  previewTitle.value = `预览简历 - ${resume.title}`

  // 确定文件URL和文件名，使用代理API解决CORS问题
  if (resume.uploaded_file) {
    // 上传的简历文件 - 使用代理API
    previewFileUrl.value = `/api/resume-management/resumes/${resume.id}/file/`
    const urlParts = resume.uploaded_file.split('/')
    const fileName = urlParts[urlParts.length - 1]
    previewFileName.value = decodeURIComponent(fileName)
  } else if (resume.generated_file_url) {
    // 已生成的简历文件 - 使用代理API
    previewFileUrl.value = `/api/resume-management/resumes/${resume.id}/file/`
    previewFileName.value = resume.generated_file_name || `${resume.title}.${resume.generated_file_type || 'docx'}`
  } else if (resume.generated_file) {
    // 旧版生成的文件 - 使用代理API
    previewFileUrl.value = `/api/resume-management/resumes/${resume.id}/file/`
    previewFileName.value = `${resume.title}.pdf`
  } else {
    // 没有生成文件，但完成度足够，先生成再预览
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    if (completionRate >= 80) {
      try {
        ElMessage.info('正在生成简历文件，请稍候...')
        await generateAndDownloadWord(resume)
        // 重新获取简历数据
        await fetchResumeList()
        // 递归调用预览（此时应该有文件了）
        setTimeout(() => handlePreview(resume), 1000)
        return
      } catch (error) {
        ElMessage.error('生成简历文件失败，无法预览')
        return
      }
    } else {
      ElMessage.warning('简历完成度不足，无法预览')
      return
    }
  }

  showPreviewDialog.value = true
}

// 处理预览下载
const handlePreviewDownload = () => {
  if (currentPreviewResume.value) {
    handleDownload(currentPreviewResume.value)
  }
}

// 检查是否可以预览
const canPreview = (resume: Resume): boolean => {
  if (resume.resume_type === 'generated') {
    // 在线生成的简历：有生成的文件或者完成度80%以上
    if (resume.generated_file_url || resume.generated_file) {
      return true
    }
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    return completionRate >= 80
  } else {
    // 上传的简历：有上传的文件就可以预览
    return !!(resume.uploaded_file)
  }
}

// 检查是否可以下载
const canDownload = (resume: Resume): boolean => {
  if (resume.resume_type === 'generated') {
    // 在线生成的简历：如果已经有生成的文件，或者完成度80%以上就可以下载
    if (resume.generated_file_url || resume.generated_file) {
      return true
    }
    const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
    return completionRate >= 80
  } else {
    // 上传的简历：有文件就可以下载
    return !!(resume.uploaded_file || resume.generated_file_url)
  }
}

// 删除重复的handleDropdownCommand函数

// 处理提交审核
const handleSubmitReview = async (resume: Resume) => {
  try {
    let message = '确定要提交这份简历进行审核吗？提交后将无法修改。'

    // 根据简历类型给出不同的提示
    if (resume.resume_type === 'uploaded') {
      if (!resume.uploaded_file) {
        ElMessage.warning('请先上传简历文件')
        return
      }
    } else {
      const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
      if (completionRate < 80) {
        ElMessage.warning(`简历完成度不足80%（当前：${completionRate}%），无法提交审核`)
        return
      }
    }

    const { value: submissionNote } = await ElMessageBox.prompt(
      message + '\n\n您可以添加提交说明（可选）：',
      '确认提交审核',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入提交说明（可选）',
        inputValidator: () => true // 允许空值
      }
    )

    await resumeApi.submitForReview(resume.id, { submission_note: submissionNote || '' })
    ElMessage.success('提交审核成功')
    fetchResumeList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.error || '提交审核失败')
    }
  }
}

// 处理查看历史版本
const handleViewVersions = async (resume: Resume) => {
  try {
    const response = await resumeApi.getResumeVersions(resume.id)

    // 创建版本历史对话框
    const versionList = response.data.versions.map((version: any) => {
      let statusText = version.status_display
      let reviewInfo = ''

      if (version.review) {
        reviewInfo = `\n审核结果：${version.review.review_status_display}\n审核人：${version.review.reviewer_name}\n审核时间：${new Date(version.review.review_date).toLocaleString()}\n审核建议：${version.review.review_comments}`
      }

      return `版本 ${version.version_number}：${version.title}\n状态：${statusText}\n提交时间：${version.submitted_at ? new Date(version.submitted_at).toLocaleString() : '未提交'}\n提交说明：${version.submission_note || '无'}${reviewInfo}`
    }).join('\n\n---\n\n')

    await ElMessageBox.alert(
      versionList || '暂无版本历史',
      `${resume.title} - 历史版本`,
      {
        confirmButtonText: '确定',
        type: 'info'
      }
    )
  } catch (error: any) {
    ElMessage.error('获取版本历史失败')
  }
}

// 处理AI审核
const handleAIReview = (_resume: Resume) => {
  ElMessage.info('AI审核功能开发中...')
}

// 处理AI评估
const handleAIEvaluation = async (resume: Resume) => {
  try {
    // 检查评估条件
    if (!canAIEvaluation(resume)) {
      let message = ''
      if (resume.resume_type === 'uploaded') {
        message = '请先上传简历文件才能进行AI评估'
      } else {
        const completionRate = parseFloat(resume.completion_rate?.toString() || '0')
        const hasGeneratedFile = !!(resume.generated_file_url || resume.generated_file)

        if (completionRate < 90) {
          message = `简历完成度需达到90%以上才能进行AI评估（当前：${completionRate}%）`
        } else if (!hasGeneratedFile) {
          message = '请先生成简历文件才能进行AI评估'
        }
      }
      ElMessage.warning(message)
      return
    }

    // 检查是否正在评估中
    if (resume.ai_evaluation_status === 'in_progress') {
      ElMessage.warning('简历正在评估中，请稍后再试')
      return
    }

    // 设置当前评估的简历
    currentEvaluationResume.value = resume

    // 显示岗位选择对话框
    showJobSelectionDialog.value = true
  } catch (error: any) {
    ElMessage.error('启动AI评估失败')
  }
}

// 处理岗位选择确认
const handleJobSelectionConfirm = async (jobId: number) => {
  if (!currentEvaluationResume.value) return

  try {
    // 提交AI评估任务
    const response = await resumeApi.submitAIEvaluation(currentEvaluationResume.value.id, { job_id: jobId })
    const result = response.data

    // 显示详细的成功消息
    ElMessage({
      message: result.message || 'AI评估已开始，正在后台处理中...',
      type: 'success',
      duration: 5000,
      showClose: true
    })

    // 如果有通知消息，显示额外的提示
    if (result.notification_message) {
      ElNotification({
        title: 'AI评估提示',
        message: result.notification_message,
        type: 'info',
        duration: 8000,
        position: 'top-right'
      })
    }

    // 开始轮询评估状态
    startEvaluationPolling(currentEvaluationResume.value.id)

    // 刷新简历列表以获取最新的评估状态
    await fetchResumeList()

  } catch (error: any) {
    console.error('启动AI评估失败:', error)
    ElMessage.error(error.response?.data?.error || '启动AI评估失败，请稍后重试')
  }
}

// 轮询评估状态
const startEvaluationPolling = (resumeId: number) => {
  const pollInterval = setInterval(async () => {
    try {
      const response = await resumeApi.getAIEvaluationStatus(resumeId)
      const statusData = response.data

      // 更新简历列表中的状态
      const resumeIndex = resumeList.value.findIndex(r => r.id === resumeId)
      if (resumeIndex !== -1) {
        resumeList.value[resumeIndex].ai_evaluation_status = statusData.evaluation_status
        resumeList.value[resumeIndex].ai_evaluation_at = statusData.evaluation_at
      }

      // 检查是否完成
      if (statusData.evaluation_status === 'completed') {
        clearInterval(pollInterval)

        // 显示成功通知
        ElNotification({
          title: 'AI评估完成',
          message: '您的简历AI评估已完成！点击通知中心查看详细结果，或在简历操作中查看和下载评估报告。',
          type: 'success',
          duration: 8000,
          position: 'top-right',
          onClick: () => {
            // 可以跳转到通知中心
            router.push('/notifications')
          }
        })

        // 如果当前正在显示该简历的评估对话框，自动刷新
        if (currentEvaluationResume.value?.id === resumeId && showEvaluationResultDialog.value) {
          // 触发评估结果对话框刷新
          showEvaluationResultDialog.value = false
          setTimeout(() => {
            showEvaluationResultDialog.value = true
          }, 100)
        }
      } else if (statusData.evaluation_status === 'failed') {
        clearInterval(pollInterval)

        // 显示失败通知
        ElNotification({
          title: 'AI评估失败',
          message: `很抱歉，AI评估失败了。${statusData.evaluation_error || '请稍后重试或联系客服。'}`,
          type: 'error',
          duration: 8000,
          position: 'top-right'
        })
      }
    } catch (error) {
      console.error('轮询评估状态失败:', error)
      // 如果轮询失败，继续尝试，但不显示错误消息
    }
  }, 3000) // 每3秒轮询一次

  // 设置最大轮询时间（10分钟）
  setTimeout(() => {
    clearInterval(pollInterval)
  }, 10 * 60 * 1000)
}

// 处理查看AI评估结果
const handleViewAIEvaluation = (resume: Resume) => {
  currentEvaluationResume.value = resume
  showEvaluationResultDialog.value = true
}

// 处理下载AI评估报告
const handleDownloadEvaluationReport = async (resume: Resume) => {
  try {
    const userStore = useUserStore()
    const response = await fetch(`/api/resume-management/resumes/${resume.id}/download_ai_evaluation/`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url

    // 生成文件名
    const fileName = `AI评估报告_${resume.title}_${new Date().toLocaleDateString()}.md`
    link.download = fileName

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('评估报告下载成功')
  } catch (error) {
    console.error('下载评估报告失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

// 处理查看审核结果
const handleViewReviewResult = async (resume: Resume) => {
  try {
    // 获取简历的审核历史
    const response = await resumeApi.getResumeVersions(resume.id)
    const versions = response.data.versions

    // 找到最新的审核记录
    const latestReview = versions.find((v: any) => v.review)?.review

    if (!latestReview) {
      ElMessage.warning('暂无审核记录')
      return
    }

    const statusMap: Record<string, string> = {
      'approved': '通过',
      'rejected': '未通过',
      'needs_revision': '待修改'
    }

    const reviewContent = `审核结果：${statusMap[latestReview.review_status] || latestReview.review_status}\n审核人：${latestReview.reviewer_name}\n审核时间：${new Date(latestReview.review_date).toLocaleString()}\n\n审核建议：\n${latestReview.review_comments}`

    await ElMessageBox.alert(
      reviewContent,
      '审核结果详情',
      {
        confirmButtonText: '确定',
        type: latestReview.review_status === 'approved' ? 'success' : 'warning'
      }
    )
  } catch (error: any) {
    ElMessage.error('获取审核结果失败')
  }
}

// 处理删除
const handleDelete = async (resume: Resume) => {
  try {
    await ElMessageBox.confirm('确定要删除这份简历吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await resumeApi.deleteResume(resume.id)
    ElMessage.success('删除成功')
    fetchResumeList()
  } catch (error: any) {
    console.log(error, "删除简历错误")
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理创建成功
const handleCreateSuccess = () => {
  fetchResumeList()
}

// 生命周期
onMounted(() => {
  fetchResumeList()

  // 监听页面可见性变化，当用户返回页面时刷新数据
  const handleVisibilityChange = () => {
    if (!document.hidden) {
      // 页面变为可见时刷新数据
      fetchResumeList()
    }
  }

  document.addEventListener('visibilitychange', handleVisibilityChange)

  // 页面卸载时移除监听器
  const cleanup = () => {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  }

  window.addEventListener('beforeunload', cleanup)
})

// 组件激活时刷新数据（用于keep-alive缓存的组件）
onActivated(() => {
  fetchResumeList()
})

// 监听路由变化，当从其他页面返回时刷新数据
watch(() => route.path, (newPath, oldPath) => {
  // 当路由变化到当前页面时，刷新数据
  if (newPath === '/resume/my' && oldPath && oldPath !== newPath) {
    fetchResumeList()
  }
}, { immediate: false })

// 监听查询参数变化，用于强制刷新
watch(() => route.query.refresh, (newRefresh) => {
  if (newRefresh && route.path === '/resume/my') {
    fetchResumeList()
    // 清除查询参数，避免重复刷新
    router.replace({ path: '/resume/my' })
  }
}, { immediate: false })
</script>

<style lang="scss" scoped>
.resume-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-extra-light);
    border-radius: 6px;
  }

  .resume-content {
    .empty-state {
      padding: 60px 0;
      text-align: center;
    }

    .resume-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 14px;
      margin-bottom: 20px;

      .resume-card {
        transition: all 0.3s ease;
        border-radius: 6px;
        overflow: hidden;
        height: 220px; // 固定高度确保一致性
        display: flex;
        flex-direction: column;

        &.card-clickable {
          cursor: pointer;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
          }
        }

        :deep(.el-card__header) {
          padding: 10px 12px 6px;
          border-bottom: 1px solid var(--border-color-extra-light);
          flex-shrink: 0;
        }

        :deep(.el-card__body) {
          padding: 8px 12px;
          flex: 1;
          overflow: hidden;
        }

        :deep(.el-card__footer) {
          padding: 8px 12px 10px;
          border-top: 1px solid var(--border-color-extra-light);
          background: var(--fill-color-extra-light);
          flex-shrink: 0;
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;

          .header-left {
            flex: 1;
            min-width: 0;

            .resume-title {
              font-size: 13px;
              font-weight: 600;
              color: var(--text-color-primary);
              margin-bottom: 4px;
              line-height: 1.2;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .resume-meta {
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              gap: 4px;
              font-size: 10px;
            }
          }

          .header-right {
            margin-left: 16px;

            .more-btn {
              color: var(--text-color-secondary);

              &:hover {
                color: var(--color-primary);
              }
            }
          }
        }

        .card-content {
          height: 100%;
          display: flex;
          flex-direction: column;

          .info-row {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 11px;
            line-height: 1.2;

            &:last-child {
              margin-bottom: 0;
            }

            .info-label {
              color: var(--text-color-secondary);
              margin-right: 6px;
              min-width: 50px;
              font-weight: 500;
              font-size: 10px;
            }

            .info-value {
              color: var(--text-color-primary);
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              font-size: 11px;
            }

            .completion-info {
              display: flex;
              align-items: center;
              gap: 8px;

              .percentage {
                font-size: 12px;
                color: var(--text-color-secondary);
                font-weight: 500;

                &.completion-success {
                  color: var(--color-success);
                }

                &.completion-warning {
                  color: var(--color-warning);
                }

                &.completion-danger {
                  color: var(--color-danger);
                }
              }

              .completion-tip {
                cursor: help;
              }
            }
          }
        }

        // 提交审核按钮区域（在卡片主体内容底部）
        .submit-section {
          margin-top: 12px;
          padding-top: 8px;
          border-top: 1px solid var(--border-color-extra-light);

          .el-button {
            font-weight: 500;
            height: 32px;
            font-size: 12px;

            &.submit-ready {
              animation: pulse-success 2s infinite;
            }

            .el-tag {
              font-size: 10px;
              height: 16px;
              line-height: 14px;
            }
          }
        }

        // Footer按钮布局样式
        .footer-actions {
          display: flex;
          gap: 6px;
          align-items: center;

          .el-button {
            flex: 1;
            min-width: 0;
            font-size: 11px;
            padding: 4px 6px;
            height: 28px;

            .el-icon {
              font-size: 12px;
            }
          }

          // 更多操作下拉菜单样式
          .dropdown-wrapper {
            flex: 0 0 auto;

            .el-dropdown {
              .el-button {
                min-width: 70px;
                font-size: 10px;
              }
            }
          }
        }

        .card-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 12px;

          .el-button {
            flex: 1;

            &:disabled {
              opacity: 0.5;
            }
          }
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

// 下拉菜单样式
:deep(.el-dropdown-menu) {
  .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      font-size: 14px;
    }
  }
}

@media (max-width: 768px) {
  .resume-list {
    .resume-content {
      .resume-grid {
        grid-template-columns: 1fr;
        gap: 16px;
      }
    }

    .filter-bar {
      .el-form {
        .el-form-item {
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .resume-list {
    .resume-content {
      .resume-grid {
        .resume-card {
          .card-header {
            .header-left {
              .resume-title {
                font-size: 16px;
              }
            }
          }

          .card-actions {
            display: flex;
            flex-direction: column;
            gap: 6px;

            .core-actions {
              display: flex;
              gap: 3px;
              align-items: center;

              .el-button {
                flex: 1;
                min-width: 0;
                font-size: 10px;
                padding: 3px 4px;
                height: 24px;

                .el-icon {
                  font-size: 11px;
                }
              }

              // 更多操作下拉菜单样式
              .dropdown-wrapper {
                flex: 0 0 auto;

                .el-dropdown {
                  .el-button {
                    min-width: 60px;
                    font-size: 9px;
                  }
                }
              }
            }

            .submit-action {
              margin-top: 1px;

              .el-button {
                width: 100%;
                font-weight: 500;
                height: 28px;
                font-size: 11px;

                &.submit-ready {
                  animation: pulse-success 2s infinite;
                }

                .el-tag {
                  font-size: 9px;
                  height: 16px;
                  line-height: 14px;
                }
              }
            }

            .secondary-actions {
              display: flex;
              gap: 6px;

              .el-button {
                flex: 1;
                font-size: 11px;
                padding: 4px 6px;
              }
            }
          }
        }
      }
    }
  }
}

// 提交审核按钮动画
.submit-ready {
  animation: pulse-success 2s infinite;
  box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.4);
}

@keyframes pulse-success {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.4);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}
</style>
